package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.Internal;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 *
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //定义两个字符串用来拼接日期和营业额的
        StringBuilder dateStringBuilder = new StringBuilder();
        StringBuilder tssb = new StringBuilder();

        //根据起始日期和结束日期，获取中间所有的日期放入数组
        List<LocalDate> dates = getDateList(begin,end);

        //循环根据日期查出当前日期的营业额，拼接
        dates.forEach(date->{
                    String turnover=reportMapper.getTurnoverStatisticsByDate(date,date.plusDays(1));
                    dateStringBuilder.append(date);
                    dateStringBuilder.append(",");
                    tssb.append(turnover==null?0:turnover);
                    tssb.append(",");
                }
                );

        String s1 = dateStringBuilder.toString();
        String s2 = tssb.toString();
        if (s1.endsWith(",") && s2.endsWith(",")){
            s1 = s1.substring(0, s1.length() - 1);
            s2 = s2.substring(0, s2.length() - 1);
        }
        //将日期和营业额拼接成串，封装 TurnoverReportVO 对象返回
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(s1);
        turnoverReportVO.setTurnoverList(s2);
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = getDateList(begin,end);
        List<Integer> totalUserList=new ArrayList<>();
        List<Integer> newUserList=new ArrayList<>();

        dates.forEach(date->{
            //获取当前日期新增的用户
            Integer newUser=reportMapper.getUserList(date,date.plusDays(1));
            newUserList.add(newUser==null?0:newUser);

            //获取截止当前日期所有的用户
            Integer totalUser=reportMapper.getUserList(null,date.plusDays(1));
            totalUserList.add(totalUser==null?0:totalUser);
                }
        );

        //拼接
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dates,","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = getDateList(begin,end);
        List<Integer> orderCountList = new ArrayList<>();//每日订单数
        List<Integer> validOrderCountList = new ArrayList<>();//每日有效订单数
        //订单总数
         Integer totalOrderCount= 0;
        //有效订单数
         Integer validOrderCount= 0;
        //订单完成率
         Double orderCompletionRate=0.0;

        for (LocalDate date : dates) {
            //获取当前日期订单总数
            Map orderMap=new HashMap<>();
            orderMap.put("begin",date);
            orderMap.put("end",date.plusDays(1));
            Integer orderCount=reportMapper.getOrderCount(orderMap)==null?0:reportMapper.getOrderCount(orderMap);
            orderCountList.add(orderCount);
            totalOrderCount=totalOrderCount+orderCount;

            //获取当前日期有效订单总数
            Map eOrderMap=new HashMap<>();
            eOrderMap.put("begin",date);
            eOrderMap.put("end",date.plusDays(1));
            eOrderMap.put("status", Orders.COMPLETED);
            Integer effectiveOrderCount=reportMapper.getOrderCount(eOrderMap)==null?0:reportMapper.getOrderCount(eOrderMap);
            validOrderCountList.add(effectiveOrderCount);
            validOrderCount=validOrderCount+effectiveOrderCount;
        }

        //获取订单完成率
        if (totalOrderCount!=0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount.doubleValue();
        }

        //封装 OrderReportVO
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dates,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);


        return orderReportVO;
    }

    /**
     * 销量排名前十统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSaleTop10(LocalDate begin, LocalDate end) {

            LinkedList<Map<String, BigDecimal>> mapList = reportMapper.getSale(begin, end);

            if (mapList == null || mapList.isEmpty()) {
                return new SalesTop10ReportVO("", ""); // 或者根据业务需求返回其他默认值
            }

            StringBuilder nameStringBuilder = new StringBuilder();
            StringBuilder numberStringBuilder = new StringBuilder();

            for (Map<String, BigDecimal> map : mapList) {

                    nameStringBuilder.append(map.get("name"));
                    numberStringBuilder.append(map.get("total").toString());
                    nameStringBuilder.append(",");
                    numberStringBuilder.append(",");

            }

            // 去掉最后一个多余的逗号
            if (nameStringBuilder.length() > 0) {
                nameStringBuilder.setLength(nameStringBuilder.length() - 1);
            }
            if (numberStringBuilder.length() > 0) {
                numberStringBuilder.setLength(numberStringBuilder.length() - 1);
            }

            return new SalesTop10ReportVO(nameStringBuilder.toString(), numberStringBuilder.toString());


    }



    /**
     * 获取日期段中的每个日期
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        //根据起始日期和结束日期，获取中间所有的日期放入数组
        List<LocalDate> dates = new ArrayList<>();

        // 循环生成日期
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dates.add(currentDate);
            currentDate = currentDate.plusDays(1); // 增加一天
        }

        return dates;
    }
}
